#!/bin/bash

# Globals
typeset -x -A _D_MODULE_FUNCTION_MAP

# Usage:
#	_d_module_set_module_path "<module_directory>"
#
# Description:
#	Set the path where the all modules are stored.
#
# Notes:
#	None
#
_d_module_set_module_path() {
	_d_module_module_path=$1
	if [ ! -d "${_d_module_module_path}" ]; then
		echo "module_set_module_path failed: no such file or directory '${_d_module_module_path}'"
		return 2
	fi
	export _d_module_module_path
	return 0
}

# Usage:
#	_d_module_set_config_path "<module_directory>"
#
# Description:
#	Set the path where the all module's configurations are stored.
#
# Notes:
#	None
#
_d_module_set_config_path() {
	_d_module_config_path=$1
	if [ ! -d "${_d_module_config_path}" ]; then
		echo "module_set_config_path failed: no such file or directory '${_d_module_config_path}'"
		return 2
	fi
	export _d_module_config_path
	return 0
}

# Usage:
#	_d_module_load "<module_name>"
#
# Description:
#	Load a module stored in the module path specified with _d_module_set_path.
#
# Notes:
#	None
#
_d_module_load() {
	_d_module_name=$1
	_d_module_config="${_d_module_config_path}/${_d_module_name}.conf"
	_d_module_directory="${_d_module_module_path}/${_d_module_name}"
	_d_module_module="${_d_module_directory}/_init"
	if [ ! -f "${_d_module_module}" ]; then
		echo "module_load failed: no such module '${_d_module_name}'"
		return 2
	fi

	# Load the module
	unset _D_MODULE_LOADED_NAME
	. ${_d_module_module}

	# Check that the module loaded
	if [ -z "${_D_MODULE_LOADED_NAME}" ]; then
		echo "module_load failed: failure while loading module '${_d_module_name}'"
		return 3
	fi

	# Initialize the module
	_d_${_D_MODULE_LOADED_NAME}_init "${_d_module_directory}" "${_d_module_config}"
	if [ $? -ne 0 ]; then return 4; fi

	# Map human readable module name to internal name
	_D_MODULE_FUNCTION_MAP[$_d_module_name]=${_D_MODULE_LOADED_NAME}

	return 0
}

# Usage:
#	_d_module_map_name "<module_name>"
#
# Description:
#	Translate the human readable <module_name> to the application friendly module identifier
#
# Notes:
#	None
#
_d_module_map_name() {
	_d_module_name=$1
	echo ${_D_MODULE_FUNCTION_MAP[$_d_module_name]}
}

# Usage:
#	_d_module_start "<module_name>" [module arguments]
#
# Description:
#	Start specified module execution
#
# Notes:
#	This always returns the return code of the module executed
#
_d_module_start() {
	_d_module_name=$1
	declare -a argv=("${!2}")
	module=$(_d_module_map_name "$_d_module_name")
	_d_${module}_start argv[@]
	return $?
}

